package com.steam.user.service.impl;

import com.steam.basic.exception.BusinessException;
import com.steam.basic.service.impl.BaseServiceImpl;
import com.steam.basic.util.Md5Utils;
import com.steam.basic.util.StrUtils;
import com.steam.user.domain.Logininfo;
import com.steam.user.domain.User;
import com.steam.user.dto.UserDto;
import com.steam.user.mapper.LogininfoMapper;
import com.steam.user.mapper.UserMapper;
import com.steam.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPwd();
        String rePwd = userDto.getRePwd();
        //空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
                ||StringUtils.isEmpty(pwd) || StringUtils.isEmpty(rePwd)){
            throw  new BusinessException("信息不能为空!!!");
        }
        //密码是否相同
        if(!pwd.equals(rePwd)){
            throw  new BusinessException("两次密码不一致!!!");
        }
        //短信验证码是否过期或是否正确
        Object codeObj = redisTemplate.opsForValue().get("register:" + phone);
        if(codeObj==null){
            throw  new BusinessException("手机验证码过期!!!");
        }
        if(!codeObj.toString().split(":")[0].equals(phoneCode)){//redis中的手机验证码 与 用户输入的手机验证码
            throw  new BusinessException("手机验证码错误!!!");
        }
        //添加到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        //添加t_logininfo 获取自增id
        logininfoMapper.save(logininfo);
        //添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    @Override
    public void emailRegister(UserDto userDto) {
        String email = userDto.getEmail();
        String pwd = userDto.getPwd();
        String rePwd = userDto.getRePwd();
        //空值校验
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(rePwd)){
            throw  new BusinessException("信息不能为空!!!");
        }
        //密码是否相同
        if(!pwd.equals(rePwd)){
            throw  new BusinessException("两次密码不一致!!!");
        }
        //添加到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        //添加t_logininfo 获取自增id
        logininfoMapper.save(logininfo);
        //添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        if (userDto.getPhone() == null){
            user.setUsername(userDto.getEmail());
            user.setEmail(userDto.getEmail());
            //生成随机盐值
            String salt = StrUtils.getComplexRandomString(32);
            //密码要加密加盐
            String md5Pwd = Md5Utils.encrypByMd5(userDto.getPwd() + salt);
            user.setSalt(salt);
            user.setPassword(md5Pwd);
            user.setState(0);
            //发送激活邮件
            /*MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom("2722938332@qq.com");
            //给用户发送邮件
            helper.setTo(userDto.getEmail());
            helper.setSubject("账号激活成功!!!");
            helper.setText("<h1>账号激活邮件!!!</h1><h3><a href='http://localhost:8080/emailActivate.html"+user.getId()+"'>点击该链接激活账号</a></h3>",true);
            javaMailSender.send(message);*/
        } else {
            user.setUsername(userDto.getPhone());
            user.setPhone(userDto.getPhone());
            //生成随机盐值
            String salt = StrUtils.getComplexRandomString(32);
            //密码要加密加盐
            String md5Pwd = Md5Utils.encrypByMd5(userDto.getPwd() + salt);
            user.setSalt(salt);
            user.setPassword(md5Pwd);
            user.setState(1);
        }
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照属性同名原则
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    @Override
    @Transactional
    public void save(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        //保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);
        //保存user
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }

    @Override
    @Transactional
    public void remove(Long id) {
        //删除登录信息logininfo
        User user = userMapper.loadById(id);
        logininfoMapper.remove(user.getLogininfoId());
        //删除user信息
        super.remove(id);
    }

    @Override
    @Transactional
    public void update(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        super.update(user);
        //获取登录信息id
        Long logininfoId = userMapper.loadById(user.getId()).getLogininfoId();
        //创建logininfo
        Logininfo logininfo = logininfoMapper.loadById(logininfoId);
        //将新的数据覆盖旧的数据
        BeanUtils.copyProperties(user,logininfo);
        logininfoMapper.update(logininfo);
    }
}
